
package com.shiku.imserver.hander;

import com.shiku.imserver.common.message.PacketVO;
import com.shiku.imserver.common.packets.ImPacket;
import com.shiku.imserver.common.tcp.TcpPacket;
import com.shiku.imserver.common.tcp.TcpServerDecoder;
import com.shiku.imserver.common.tcp.TcpServerEncoder;
import com.shiku.imserver.service.IMBeanUtils;

import java.nio.ByteBuffer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.Tio;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;

public class TcpServerHandler extends AbstractProtocolHandler {
    Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);

    public TcpServerHandler() {
    }

    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        ImPacket impacket = (ImPacket) packet;
        PacketVO result = IMBeanUtils.getMessageProcess().dispatch(impacket, channelContext);
        if (null != result) {
            Tio.bSend(channelContext, new TcpPacket(result.getCmd(), result.getBytes()));
        }

    }

    @Override
    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        ImPacket impacket = (ImPacket) packet;
        TcpPacket tcpPacket = null;
        if (packet instanceof TcpPacket) {
            tcpPacket = (TcpPacket) impacket;
        } else {
            tcpPacket = new TcpPacket(impacket.getCommand(), impacket.getBytes());
        }

        return TcpServerEncoder.encode(tcpPacket, groupContext, channelContext);
    }

    @Override
    public TcpPacket decode(ByteBuffer buffer, ChannelContext channelContext) throws AioDecodeException {
        TcpPacket tcpPacket = TcpServerDecoder.decode(buffer, channelContext);
        return tcpPacket;
    }
}
